package com.resou.reader.bookstore;

import android.content.Context;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.RequestOptions;
import com.resou.reader.MainActivity;
import com.resou.reader.R;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.api.entry.ResultList;
import com.resou.reader.base.ResouBaseFragment;
import com.resou.reader.bookstore.freezone.FreezoneActivity;
import com.resou.reader.bookstore.more.MoreActivity;
import com.resou.reader.data.bookstore.model.BasicList;
import com.resou.reader.data.bookstore.model.PlateNovels;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.userinfo.UserInfoActivity;
import com.resou.reader.reader.utils.ScreenUtils;
import com.resou.reader.reader.utils.ViewUtils;
import com.resou.reader.search.search2.Search2Activity;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.StatusBarUtil;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.ViewSizeUtils;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.utils.eventbus.RefreshStoreEvent;
import com.resou.reader.utils.eventbus.UpdateUserIconEvent;
import com.resou.reader.view.Loading;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.raphets.roundimageview.RoundImageView;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class HomeBookStoreFragment extends ResouBaseFragment<BookStorePresenter> implements IBookStoreView, View.OnClickListener, BookStoreMainAdapter.OnStoreMainAdapterInteractionListener {
    private static final String TAG = HomeBookStoreFragment.class.getSimpleName();

    @BindView(R.id.image_search)
    ImageView imageSearch;
    @BindView(R.id.search_layout)
    FrameLayout searchLayout;
    @BindView(R.id.search_bar)
    LinearLayout searchBar;

    @BindView(R.id.store_container)
    RelativeLayout storeContainer;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView myrecyclerView;
    @BindView(R.id.profile_image)
    RoundImageView profileImage;


    BookStoreMainAdapter mAdapter;
    private MainActivity mMainActivity;
    float banner_height = 0;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mMainActivity = (MainActivity) context;
    }

    @Override
    protected void initView() {
        System.out.println("齐刘海高度:" + mMainActivity.getState());
        searchBar.getBackground().setAlpha(0);
        int height = ViewSizeUtils.getStatusBarHeight(mActivity.getResources()) + mMainActivity.getState();
        searchBar.setPadding(0, height, 0, 0);


        float pixel = ScreenUtils.convertDpToPixel(8, mActivity);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        myrecyclerView.setItemViewCacheSize(100);
        myrecyclerView.setLayoutManager(layoutManager);
        mAdapter = new BookStoreMainAdapter(getActivity());
        mAdapter.setInteractionListener(this);
        myrecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                if (mAdapter.getItemViewType(parent.getChildAdapterPosition(view)) == 111) {
                    return;
                }
                if (parent.getChildAdapterPosition(view) == mAdapter.getItemCount() - 1) {
                    return;
                }
                outRect.bottom = (int) pixel;
            }
        });
        myrecyclerView.setAdapter(mAdapter);

        swipeRefreshLayout.setOnRefreshListener(this::initData);
        swipeRefreshLayout.setColorSchemeColors(mActivity.getResources().getColor(R.color.btn_login_highlight));

        initUserPic();
        profileImage.setOnClickListener(v -> {
            UserInfoActivity.start(mActivity);

        });
        // TODO 需要动态获取空间高度，暂时写死 szc
        banner_height = ScreenUtils.convertDpToPixel(223 - 50, getContext()) - ViewSizeUtils.getStatusBarHeight(getResources());
        myrecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {


            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (banner_height >= getScollYDistance()) {
                    float alpha = getScollYDistance() / banner_height * 255;
                    searchBar.getBackground().setAlpha((int) alpha);
                }

                int topRowVerticalPosition =
                        (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                swipeRefreshLayout.setEnabled(topRowVerticalPosition >= 0 && recyclerView != null && !recyclerView.canScrollVertically(-1));

            }

        });
    }


    public int getScollYDistance() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) myrecyclerView.getLayoutManager();
        int position = layoutManager.findFirstVisibleItemPosition();
        if (position > 0) {
            return (int) banner_height;
        } else {
            View firstVisiableChildView = layoutManager.findViewByPosition(position);
            return -firstVisiableChildView.getTop();
        }


    }

    @Override
    protected void retryRefreshData() {
        initData();
    }

    private void initUserPic() {
        if (UserInstance.isLogin()) {
            LoginData loginData = UserInstance.getLoginData();
            if (loginData != null) {
                String headPic = loginData.getHead_pic();
                if (headPic != null) {
                    Glide.with(this).setDefaultRequestOptions(new RequestOptions().format(DecodeFormat.PREFER_RGB_565)).load(headPic).into(profileImage);
                } else {
                    Glide.with(this).setDefaultRequestOptions(new RequestOptions().format(DecodeFormat.PREFER_RGB_565)).load(R.mipmap.user_head).into(profileImage);
                }
            }
        }
    }

    /**
     * 用户修改头像后同步刷新
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UpdateUserIconEvent event) {
        Loading.getInstance().dismiss();
        if (PreferenceUtil.getInstance(getContext()).getUserIcon() != null) {
            profileImage.setImageURI(Uri.parse(PreferenceUtil.getInstance(getContext()).getUserIcon()));
        }
    }

    @Override
    protected void initPresenter() {
        mPresenter = new BookStorePresenter(this);
    }

    @OnClick({R.id.search_layout})
    public void onClick(View v) {
        if (v == searchLayout) {
            Search2Activity.start(getActivity());
        }
    }

    @Override
    public void setData(List<Object> objects) {
        mAdapter.setData(objects);
    }

    @Override
    public void getRepeatList(ResultList<PlateNovels> objects) {
        BasicList<PlateNovels> basicList = new BasicList<>();
        basicList.setLimitFreeTimeMs(0);
        basicList.setPlateName("往期经典");
        basicList.setPlateType("42");
        basicList.setShowType(0);
        basicList.setViewType(0);
        basicList.setPlateNovels(objects.getData());
        List<Object> objectList = mAdapter.getData();
        if (objectList != null) {
            objectList.set(position, basicList);
            mAdapter.notifyItemChanged(position, mAdapter.TYPE_EDITOR_RECOMMEND);
        }
    }

    private int position;

    @Override
    public void finishRefresh() {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_book_store;
    }

    @Override
    public void showContent() {
        swipeRefreshLayout.setVisibility(View.VISIBLE);
        myrecyclerView.setVisibility(View.VISIBLE);
        dissLoading();
    }

    @Override
    public void showProgress() {
        showLoading();
        swipeRefreshLayout.setVisibility(View.GONE);
    }

    @Override
    public void showError(Throwable throwable) {
        dissLoading();
        swipeRefreshLayout.setVisibility(View.GONE);
        showNetErrorView(R.id.store_container);
        if (!NetworkUtils.isNetworkConnected(getContext())) {
            ToastUtil.makeShortToast("网络异常");
        } else {
            ToastUtil.makeShortToast("数据异常，请稍后重试");
        }
    }

    @Override
    public void showEmpty() {

    }

    @Override
    public void initData() {
        if (!UserInstance.isTourist()) {
            String gender = UserInstance.getLoginData().getGender();
            mPresenter.loadBookStoreInfo(gender);
        } else {
            int gender = PreferenceUtil.getInstance(mActivity).loadUserGender();
            if (gender == 1) {
                mPresenter.loadBookStoreInfo(String.valueOf(gender));
            } else if (gender == 2) {
                mPresenter.loadBookStoreInfo(String.valueOf(gender));
            } else {
                mPresenter.loadBookStoreInfo("");
            }
        }
    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        assert rootView != null;
//        unbinder = ButterKnife.bind(this, rootView);
        StatusBarUtil.setStatusBarColor(getActivity(), getResources().getColor(android.R.color.transparent));
        EventBus.getDefault().register(this);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        //unbinder.unbind();    }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        initUserPic();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefreshStoreEvent event) {
        initData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            System.out.println("class:" + this.getClass().getName() + "\thidden:" + hidden);
            StatusBarUtil.setStatusBarColor(getActivity(), getResources().getColor(android.R.color.transparent));
        }
    }

    @Override
    public void onMoreClicked(String plateName, String plateType) {
        if ("55".equals(plateType)) {
            FreezoneActivity.start(getContext());
            return;
        }
        if (!"42".equals(plateType)) {
            MoreActivity.start(mActivity, plateName, plateType);
        }
    }

    @Override
    public void onMorePositionClicked(int position, String plateName, String plateType) {
        if ("42".equals(plateType)) {
            this.position = position;
            mPresenter.getRepeatList();
        }

    }

}
